<?php
include '../login/db_connect.php';
include '../login/functions.php';
sec_session_start ();
if (isset ( $_COOKIE ['login_string'] )) {
	$login_string = $_COOKIE ['login_string'];
	$username = $_COOKIE ['username'];
	$user_id = $_COOKIE ['user_id'];
	
	$_SESSION ['user_id'] = $user_id;
	$_SESSION ['login_string'] = $login_string;
	$_SESSION ['username'] = $username;
}
if (login_check ( $mysqli ) == true) {
	$username = $_SESSION ['username'];
	global $ruolo;
	$query_ruolo="SELECT ruolo, saldo FROM members WHERE username='".$username."' LIMIT 1";
	if ($result = $mysqli->query ($query_ruolo )) {
		while ( $row = $result->fetch_assoc () ) {
			$ruolo=$row['ruolo'];
		}
		$result->free();
	}
?>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link type=text/css rel="stylesheet" href='../css/catalog.css'>
<title>Gestione listini</title>
<!-- Bootstrap -->
<!-- jQuery (necessario per i plugin Javascript di Bootstrap) -->
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> -->
<!-- Includi tutti i plugin compilati (sotto), o includi solo i file individuali necessari -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../js/bootstrap.min.js"></script>
<link href="../css/bootstrap.min.css" rel="stylesheet">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js non funziona se guardate la pagina attraverso file:// -->
<!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
<script type="text/javascript">
	vendor="";
	cadd=0;
	flag=true;
	function venditore(id,appellativo){
		this.id = id;
		this.appellativo = appellativo;
	}
	function fetch_vendors(){
		var request=new XMLHttpRequest();
		
		request.open("POST", "./process_catalog.php",true);
		// POST to a server-side script
		// Send the message, in json, as the request body
		request.setRequestHeader("Content-Type", "application/json");
		request.onreadystatechange = function() {
			// Define event listener
			// If the request is compete and was successful 
			if (request.readyState === 4 && request.status === 200) {
				//risposta = JSON.parse(request.responseText);
				elenco_fornitori=JSON.parse(request.responseText);
				lista=document.getElementById('lista_fornitori');

				for (var i=0;i<elenco_fornitori.length;i++){
					nuovoListItem=document.createElement("li");
					nuovoListItem.innerHTML="<a href='javascript:void(0)' onclick='selectVendor(this);'>"+elenco_fornitori[i].appellative+"</a>"
					lista.appendChild(nuovoListItem); 
				}
				$('#lista_fornitori').children().slice(2,this.length).css("display","none");
				divider=document.createElement("li");
				divider.setAttribute("class","divider");
				altri=document.createElement("li");
				altri.innerHTML="<a id='altri'>Altri <span class='caret'></span></a>";
				lista.appendChild(divider);
				lista.appendChild(altri);

				//associo al link "altri" una funzione che espande i risultati di #menu_fornitori
				$('#altri').click(function(e) {
					  e.stopPropagation();
					  // ... faccio qualcosa ...
					  flag= flag ? false:true;
					  
					  if(!flag){
					  $('#lista_fornitori').children().css("display","initial");
					  $('#altri').attr('class','dropup');
					  }
					  else{
						 $('#lista_fornitori').children().slice(2,elenco_fornitori.length).css("display","none");
						$('#altri').removeClass('dropup');
					  }
					});
				
				$('#drop').on('hide.bs.dropdown', function (e) {
					$('#lista_fornitori').children().slice(2,elenco_fornitori.length).css("display","none");
					$('#altri').removeClass('dropup');
					$("#vendor").on('input', handler)
					});
				$('#drop').on('show.bs.dropdown', function (e) {
					$("#vendor").off('input', handler)});
				//$("#vendor").on('input',handler_search);
				handler=function(){
									$('#vendor').trigger('click');
								  $('#vendor').off('input',handler);
								  $("#vendor").on('keyup',handler_search);
				}
				
				
				handler_search = function (){
					
					stringa=$('#vendor').val();
					regular = new RegExp(stringa,"i");
					$('#lista_fornitori').children().css("display","initial");
					
					if(stringa==""){
						$('#lista_fornitori').children().css("display","initial");
						$('#lista_fornitori').children().slice(2,elenco_fornitori.length).css("display","none");
					}
					else{
						
						$('#lista_fornitori').children().css("display","initial");
						$('#lista_fornitori').children().last().css("display","none");
						$('#lista_fornitori').children().last().prev().css("display","none");
						$('#lista_fornitori').children().each(function(index){
								if(!regular.test($(this).first().first().text()))
										$(this).css("display","none");
							})
						
					}
				}
				
				$("#vendor").on('input', handler);
				$("#vendor").on('keyup',handler_search);
			}
			
		
			
		//var str=JSON.stringify(data);
		
		}
		
		request.send(null);
// 		elemento=document.getElementById('altri');
// 		elemento.addEventListener('click',others,true);
	}
	
	function show_vendors(){
		$('#vendor').trigger('click');
	}
	function selectVendor(element){
		vendor=element.firstChild.nodeValue;
		document.getElementById('vendor').value=vendor;
		for (var q=0;q<elenco_fornitori.length;q++){
			if(elenco_fornitori[q].appellative==vendor){
				selected=elenco_fornitori[q].id_vendor;break;
			}
		}
		
		//carica(selected);
			$.ajax({
	  // definisco il tipo della chiamata
	  type: "POST",
	  // specifico la URL della risorsa da contattare
	  url: "./process_catalog.php",
	  // passo dei dati alla risorsa remota
	  data: {"id":selected},
	  // definisco il formato della risposta
	  dataType: "text",
	  // imposto un'azione per il caso di successo
	  success: function(risposta){
		   loadCatalog(risposta);
		  //else reportEmptyMessage();
		  
	    //document.write(JSON.parse(risposta)[0].description);
	 },
	  // ed una per il caso di fallimento
	  error: function(){
	    alert("Errore di connessione");
	  }
		})
		
	}
	function loadCatalog(risp){
		$('#listino tr[id!=intestazione]').remove();
		$('#new').removeClass('hidden');
		$('#remove_listino').removeClass('hidden');
		if (cadd==0){$('#new').on('click',addrow);
		$('#remove_listino').on('click',function(){$('#listino tr[id!=intestazione]').remove();
		$.ajax({
			  // definisco il tipo della chiamata
			  type: "POST",
			  // specifico la URL della risorsa da contattare
			  url: "./process_update_insert.php",
			  // passo dei dati alla risorsa remota
			  data: {"vendor":selected+"C"},
			  // definisco il formato della risposta
			  dataType: "text",
			  // imposto un'azione per il caso di successo
			  success: function(risposta){
				 
				 
				  //else reportEmptyMessage();
				  
			    //document.write(JSON.parse(risposta)[0].description);
			 },
			  // ed una per il caso di fallimento
			  error: function(){
			    alert("Errore di connessione");
			  }
				})

		}); cadd++}
		obj=JSON.parse(risp);
		length=obj.length;
		
		

		//document.write(table.find("[name=customized]").val());
		for (var i=0;i<obj.length;i++){
			var c=$("<tr><td><input name=product_id type=hidden size=4 maxlength=4><td><input name=initials type=text placeholder=???? size=4 maxlength=4>"+ 
					"<td><input name=description type=text size=35 data-toggle='tooltip' data-placement='bottom'>" 
	+"<td><input name=price type=text size=5 maxlength=5 data-toggle='popover' data-placement='bottom'>"

	+"<td><input name=customized type=text size=10><select name=units>"
																		+"<option value=-->--"
																		+"<option value=kg>kg" 
																		+"<option value=g>g"
																		+"<option value=lt>lt"
																	+"<option value=pezzo>pezzo" 
																	+"<option value=piede>piede"
																	+"<option value=pacco>pacco"
																	+"</select>" 
		+"<td>&nbsp;&nbsp;&nbsp;&nbsp;<input name=visible type=checkbox>"  
		+"<td><button name=remove class=close aria-label=Close><span aria-hidden=true>&times;</span></button></tr>");
			c.find("[name=product_id]").val(obj[i].product_id);
			c.find("[name=initials]").val(obj[i].initials);
			c.find("[name=description]").val(obj[i].description);
			c.find("[name=price]").val(obj[i].price);
			units=obj[i].units.split(" ");
			
			for (var f=0;f<units.length;f++){
				if (f==(units.length-1)){c.find("option[value="+units[f]+"]").attr('selected','selected');break;}
				if (units[i]!='')c.find("[name=customized]").val(c.find("[name=customized]").val()+units[f]+" ");
			}
			vis=obj[i].visibility;
			if(vis==1) {c.find("[name=visible]").attr('checked','checked');}
			c.find('input').on('change',update);
			c.find('select').on('change',update);
			c.find('[name=remove]').on('click',remove);
			$('#listino').append(c);
			
			
		}
		
	}
	addrow = function(){
		last_description = $('#listino').find('[name=description]').last();
		if(last_description.val() == ''){last_description.focus();last_description.addClass('bg-danger');last_description.tooltip({title:'compila questo campo'});return;}
		
		var c=$("<tr><td><input name=product_id type=hidden size=4 maxlength=4><td><input name=initials type=text placeholder=???? size=4 maxlength=4>"+ 
				"<td><input name=description type=text size=35 data-toggle='tooltip' data-placement='bottom'>" 
+"<td><input name=price type=text size=5 maxlength=5 data-toggle='popover' data-placement='bottom'>"

+"<td><input name=customized type=text size=10><select name=units>"
																	+"<option value=-->--"
																	+"<option value=lt>lt"
																	+"<option value=kg>kg" 
																	+"<option value=g>g" 
																+"<option value=pezzo>pezzo" 
																+"<option value=piede>piede"
																+"<option value=pacco>pacco"
																+"</select>" 
	+"<td>&nbsp;&nbsp;&nbsp;&nbsp;<input name=visible type=checkbox checked>"  
	+"<td><button name=remove class=close aria-label=Close><span aria-hidden=true>&times;</span></button></tr>");
		c.find('[name=remove]').on('click',remove);
		c.find('[name=units]').on('change',update);
		all_input=c.find('input');
		
		all_input.each(function(index){$(this).on('change',update)});
		$('#listino').append(c);
		
		$.ajax({
			  // definisco il tipo della chiamata
			  type: "POST",
			  // specifico la URL della risorsa da contattare
			  url: "./process_update_insert.php",
			  // passo dei dati alla risorsa remota
			  data: {"vendor":selected},
			  // definisco il formato della risposta
			  dataType: "text",
			  // imposto un'azione per il caso di successo
			  success: function(risposta){
				  var id=JSON.parse(risposta);
				  var l=$('#listino').children().length;
				  $('[name=product_id]').last().val(id.id);
				  
				  //else reportEmptyMessage();
				  
			    //document.write(JSON.parse(risposta)[0].description);
			 },
			  // ed una per il caso di fallimento
			  error: function(){
			    alert("Errore di connessione");
			  }
				})
	}
	remove = function(e){
		
		riga=$(this).parent().parent();
		
		product_id=riga.find("[name=product_id]").val();
		riga.remove();
		$.ajax({
			  // definisco il tipo della chiamata
			  type: "POST",
			  // specifico la URL della risorsa da contattare
			  url: "./process_update_insert.php",
			  // passo dei dati alla risorsa remota
			  data: {"id":product_id},
			  // definisco il formato della risposta
			  dataType: "text",
			  	success: function(risposta){
			  	},
			 // ed una per il caso di fallimento
			    error: function(){
			    alert("Errore di connessione");
			  }
				})
	}
	 update=function(e){
		campo="";
		var res=check($(this));
		if(res==0)return;
		riga=$(this).parent().parent();
		if($(this).attr('name')=='customized'){
			valore=$(this).val()+" "+$(this).next().val();	
				//valore=$(this).val();
			campo="units";
		}
		else if($(this).attr('name')=='units'){
			valore=$(this).prev().val()+" "+$(this).val();	
				//valore=$(this).val();
			campo="units";
		}
		else if($(this).attr('name')=='visible'){valore=$(this).prop('checked')?'1':'false';campo="visibility";}
		else {valore=$(this).val();campo=$(this).attr('name');}
		product_id=riga.find("[name=product_id]").val();
		if (valore=="") valore='NULL';
		var field_to_modify={"id":product_id, "val":valore, "campo":campo}
		//alert(JSON.stringify(field_to_modify));
		$.ajax({
	  // definisco il tipo della chiamata
	  type: "POST",
	  // specifico la URL della risorsa da contattare
	  url: "./process_update_insert.php",
	  // passo dei dati alla risorsa remota
	  data: JSON.stringify(field_to_modify),
	  // definisco il formato della risposta
	  dataType: "text",
	  	success: function(risposta){
		  	//alert(risposta);
	  	},
	 // ed una per il caso di fallimento
	    error: function(){
	    alert("Errore di connessione");
	  }
		})
		
		
	}
	function check(elem){
		nome=elem.attr('name');
		switch(nome){
		case 'initials':if(elem.val()=="")return 1;
						return 1;
						
		case 'description': if(elem.val()=="") {elem.attr('title','compila questo campo');
												elem.tooltip();
												
												
												elem.addClass('bg-danger');
												
												return 0;
												}
							else {elem.removeAttr('title');	 
									elem.tooltip('destroy');
									
									elem.removeClass('bg-danger');
									return 1;
							}
		case 'price': if (isNaN(elem.val())) {	//elem.attr('title','esempi');
												elem.popover({html:true,trigger:'hover',content:'12,5 NO - 12.5 SI<br> abcd... NO',title:'esempi'});
												
												elem.popover('show');
												elem.addClass('bg-danger');
													return 0;
						}
						elem.popover('destroy');
						elem.removeClass('bg-danger');
						return 1;
											
		default: return 1;
		}
	}
	
</script>
</head>
<body onload="fetch_vendors()">
	<!-- 	barra di navigazione -->
	<nav class="navbar navbar-inverse navbar-static-top" role="navigation">
		<div class="container">
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collapsed"
					data-toggle="collapse" data-target="#menu_links">
					<span class="sr-only">Toggle navigation</span> <span
						class="icon-bar"></span> <span class="icon-bar"></span> <span
						class="icon-bar"></span>
				</button>
				<a href="./home.php"><img src="../images/logo.png" height=45px
					width=45px></a>
			</div>
			<div class="collapse navbar-collapse" id=menu_links>
				<ul class="nav navbar-nav">
					<li><a href="./home.php"><span class="glyphicon glyphicon-home"
							aria-hidden="true"></span>&nbsp;Home</a></li>
					<li><a href="profile.php">Profile</a></li>
					<li><a href="messages">Messages</a></li>
				</ul>
				<p class="navbar-text navbar-right">
					Signed in as <a href="#" class="navbar-link"><mark><?php echo $username?></mark></a>&nbsp;&nbsp;&nbsp;<a
						href="../login/logout.php" class="navbar-link"><span
						class="glyphicon glyphicon-log-out" aria-hidden="true"></span>Logout</a>
				</p>
			</div>
		</div>
	</nav>

	<!-- inizio del contenitore della pagina -->
	<div class=container-fluid>
		<div class="panel panel-primary">
			<!-- Default panel contents -->
			<div class="panel-heading">LISTINO PREZZI</div>
			<div class="panel-body">
				<div id=drop class="btn-group">
					<label for="ricerca_vendor">Seleziona un fornitore</label> <input
						id=vendor type="search" value=""
						class="form-control dropdown-toggle" data-toggle="dropdown"
						placeholder="Digita un appellativo">
					<ul id=lista_fornitori class="dropdown-menu" role="menu">
					</ul>
				</div>
			</div>

			<!-- Table -->


			<!-- 				<div class=row> -->
			<!-- 					<div class='col-xs-2'><h4><span class="label label-primary">Settore</span></h4></div> -->
			<!-- 					<div class='col-xs-4'><h4><span class="label label-primary">Descrizione</span></h4></div> -->
			<!-- 					<div class='col-xs-2' align='center'><h4><span class="label label-primary">Prezzo</span></h4></div> -->
			<!-- 					<div class='col-xs-2'><h4><span class="label label-primary">Misura</span></h4></div> -->
			<!-- 					<div class='col-xs-1'><h5><span class="label label-primary">Mostra</span></h5></div> -->
			<!-- 				</div> -->
			<!-- 				<div class=row> -->
			<!-- 					<div class='col-xs-2'> -->
			<!-- 						<input name=sigla type=text value='????' size=4 maxlength=4> -->
			<!-- 					</div> -->
			<!-- 					<div class='col-xs-4'> -->
			<!-- 						<input name=description type=text value='mele golden'> -->
			<!-- 					</div> -->
			<!-- 					<div class='col-xs-2' align='center'> -->
			<!-- 						<input name=prezzo type=text size=3 maxlength=4> -->
			<!-- 					</div> -->
			<!-- 					<div class='col-xs-2'> -->
			<!-- 						<select name=units> -->
			<!-- 							<option value=lt>lt -->
			<!-- 							<option value=kg>kg  -->
			<!--  							<option value=g>g  -->
			<!-- 							<option value=pezzo>pezzo/i  -->
			<!-- 							<option value=piede>piede/i																	 -->
			<!-- 						</select>  -->
			<!-- 					</div> -->
			<!-- 					<div class='col-xs-1'> -->
			<!-- 						<input name=visible type=checkbox> -->
			<!-- 					</div> -->
			<!-- 				</div> -->


			<div class=table-responsive>
				<table id=listino class='table'>
					<tr id='intestazione'>
						<th>
						
						<th><h4>
								<span class='label label-primary'>Sigla</span>
							</h4>
						
						<th><h4>
								<span class='label label-primary'>Descrizione</span>
							</h4>
						
						<th><h4>
								<span class='label label-primary'>Prezzo/&euro;</span>
							</h4>
						
						<th><h4>
								<span class='label label-primary'>Misura</span>
							</h4>
						
						<th><h4>
								<span class='label label-primary'>Mostra</span>
							</h4>
						
						<th>
				
				</table>


			</div>

		</div>

		<button id=new type="button" class="btn btn-warning pull-left hidden">Nuovo
			record</button>&nbsp;<button id=remove_listino type="button" class="btn btn-danger pull-right hidden">Cancella listino</button>


</body>
</html>

<?php
} else {
	header ( "Location: ../login/login.php" );
	// echo 'You are not authorized to access this page, please login. <br/>';
}
?>










